<template>
  <div>
    <div class="title">
      <div class="desc">奖金总额：{{ totalNum }}元</div>
      <div>
        <el-button type="primary" @click="handleAdd" :disabled="flag == 3">添加</el-button>
      </div>
    </div>
    <!-- {{membersList}} -->
    <el-table
      :data="membersList"
      class="table"
      v-loading="datadetail.detail_loading"
      element-loading-text="正在加载关联对象数据"
    >
      <el-table-column label="姓名" width="260">
        <template #default="scope">
          <user-list-modal
            style="width: 100%"
            :disabled="flag == 3"
            v-model="scope.row.expertName"
            @update:modelValue="(val) => handleProjectLeader(val, scope.$index)"
            :default-users="[]"
            :multiple="false"
            :devType="'platform'"
          />
        </template>
      </el-table-column>

      <el-table-column label="发薪单位" width="260">
        <template #default="scope">
          <popup-tree-input
            v-if="activeIndex == scope.$index"
            :data="orgAllList"
            :props="popupTreeProps"
            :prop="
              scope.row.workUnitName == null ? $t('message.org.top_menu') : scope.row.workUnitName
            "
            :current-change-handle="(item) => selectCompany(item, scope.row)"
            clearable
            node-key="0"
          />
          <!--              <span v-else>{{ scope.row.workUnitId }}</span>-->
          <span v-else>{{ scope.row.workUnitName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="金额" width="150">
        <template #default="scope">
          <el-input
            v-if="activeIndex == scope.$index"
            v-model="scope.row.workContent"
            maxlength="10"
            @input="scope.row.workContent = NumberCheck(scope.row.workContent)"
            placeholder="金额"
          ></el-input>
          <span v-else>{{ scope.row.workContent }}</span>
        </template>
      </el-table-column>

      <el-table-column align="right" width="250">
        <template #header>
          <span>操作</span>
        </template>
        <template #default="scope">
          <div v-if="activeIndex == scope.$index">
            <el-button type="default" @click="handleSaveRow(scope.row)">保存</el-button>
            <el-button type="success" @click="confirm()">取消</el-button>
            <el-popconfirm
              @confirm="handleDelete(scope.$index)"
              width="220"
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon-color="#e6a23c"
              title="你确定要删除当前行?"
            >
              <template #reference>
                <el-button type="danger" :disabled="flag == 3">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
          <div v-else>
            <el-button type="primary" @click="handleEdit(scope.$index)" :disabled="flag == 3"
              >编辑</el-button
            >
            <el-popconfirm
              @confirm="handleDelete(scope.$index)"
              width="220"
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon-color="#e6a23c"
              title="你确定要删除当前行?"
            >
              <template #reference>
                <el-button type="danger" :disabled="flag == 3">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { tips } from '@/views/science/components/tips/tips'
import { projectManagementListPage } from '@/views/science/technologyStrength/api/technologyStrength'
import UserListModal from '@/views/project/components/UserListModal/index.vue'
import request from '@/utils/request'
import * as proxy from '@/constants/proxy'
import { NumberCheck } from '@/utils/utils'

import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue'
export default {
  components: {
    UserListModal,
    PopupTreeInput,
  },
  emits: {
    dataChange: null,
    paramsChange: null,
  },
  props: {
    orgAllList: {
      type: Array,
      default: () => [],
    },
    members: {
      type: Array,
      required: true,
    },
    // falg  1:新增  2:编辑  3:详情
    flag: {
      type: String,
      default: '1',
    },
    bonusdandu: {
      type: String || Number,
      default: 1,
    },
    defaultList: {
      type: Array,
      default: () => [],
    },
  },
  setup(props, { emit }) {
    onMounted(() => {
      let list = props.defaultList.map((e) => {
        return {
          "expertNameId": e.applyUserId,
          "expertName": e.applyUser,
          "workUnitName": e.orgName, 
          "workUnitNameId": e.orgId,
          "workContent": e.amount,
        }
      })
      membersList.value = list
      emit('paramsChange', membersList.value)
    })
    let activeIndex = ref(-1)
    const popupTreeProps = {
      label: 'name',
      children: 'children',
    }
    const selectCompany = (item, row) => {
      row.workUnitId = item.id
      row.workUnitName = item.name
    }

    let handleProjectLeader = (user: any, index: number) => {
      console.log(user, index)
      let array = membersList.value.map((e) => e.expertNameId)
      if (array.indexOf(user.userId) != -1) {
        tips('不能重复选择同一个人', 'warning')
        membersList.value[index].expertNameId = ''
        membersList.value[index].expertName = ''
        return false
      }
      // if(index || index === 0) tableIndex.value = index;
      membersList.value[index].expertNameId = user.userId
      membersList.value[index].expertName = user.cname
      getPeople(user.userCode, index)
      console.log(membersList)
    }

    const getPeople = (id: string, index: number) => {
      return request({
        url: proxy.CHECC_API_CMS + '/user/getList',
        method: 'post',
        data: { empcode: id },
      }).then((res) => {
        console.log('res', res.data.data.records[0])
        let resdata = res.data.data.records[0]
        // const row = membersList.value[tableIndex.value]
        membersList.value[index].workUnitId = resdata.orgid
        membersList.value[index].workUnitName = resdata.orgname
        // row.workUnitId = resdata.orgid
        // row.workUnitName = resdata.orgname
        console.log(membersList)
      })
    }
    const tableIndex = ref<number>(0)
    const membersList = ref(props.members)
    const bonusdandulist = ref((props.bonusdandu * 10000).toFixed(2))
    const totalNum = ref((props.bonusdandu * 10000).toFixed(2))

    watch(props, (newValue, oldValue) => {
      const mval = membersList.value
      if (mval.length) {
        console.log(mval)
        let total = (props.bonusdandu * 10000).toFixed(2)
        let num = eval(mval.map((e) => Number(e.workContent)).join('+'))
        let val = (Number(total) - num).toFixed(2)
        console.log(total,'totaldasdasd');
        
        if (Number(val) < 0) {
          console.log(num,'numasfas');
          tips('不能超过奖金总额', 'warning')
        } else {
          bonusdandulist.value = val
        }
      }
    })

    const datadetail = reactive({
      detail_loading: false,
    })

    const handleAdd = () => {
      let item = {
        expertNameId: '',
        expertName: '',
        workUnitName: '',
        workUnitNameId: '',
        workContent: bonusdandulist.value,
        status: 1,
      }

      membersList.value.push(item)

      activeIndex.value = membersList.value.length - 1
    }

    const handleEdit = (index: number) => {
      activeIndex.value = index
    }

    const handleSave = () => {
      if (membersList.value.length < 1) {
        // tips("科研学术奖励中需要至少一条数据", "warning");
        // // event.stopPropagation();
        // return false;
      } else {
        let panduan = 0
        membersList.value.forEach((item) => {
          for (let i = 0; i < membersList.value.length; i++) {
            if (item.workUnitName == null || item.workUnitName == '') {
              panduan = 1
            }
            if (item.workContent == null || item.workContent == '') {
              panduan = 2
            }
          }
        })
        if (panduan == 1) {
          tips('数据中发薪单位不能为空', 'warning')
          // event.stopPropagation();
          return false
        } else if (panduan == 2) {
          tips('金额不能为空', 'warning')
          return false
        }
      }

      activeIndex.value = -1

      emit('paramsChange', membersList.value)
    }
    const handleSaveRow = (row) => {
      let panduan = -1
      if (row.expertName == null || row.expertName == '') {
        panduan = 0
      } else if (row.workUnitName == null || row.workUnitName == '') {
        panduan = 1
      } else if (row.workContent == null || row.workContent == '') {
        panduan = 2
      }
      if (panduan == 1) {
        tips('数据中发薪单位不能为空', 'warning')
        return
      } else if (panduan == 2) {
        tips('金额不能为空', 'warning')
        return
      } else if (panduan == 0) {
        tips('人员不能为空', 'warning')
        return
      }
      activeIndex.value = -1
    }
    const handleDelete = (index: number) => {
      membersList.value.splice(index, 1)

      emit('paramsChange', membersList.value)
    }
    const confirm = () => {
      activeIndex.value = -1
    }
    const reset = () => {
      membersList.value = []
    }
    return {
      totalNum,
      reset,
      membersList,
      bonusdandulist,
      activeIndex,
      handleAdd,
      handleEdit,
      handleSave,
      handleSaveRow,
      confirm,
      handleDelete,
      NumberCheck,
      open,

      datadetail,
      handleProjectLeader,
      popupTreeProps,
      selectCompany,
    }
  },
}
</script>

<style scoped lang="scss">
.title {
  display: flex;
  justify-content: space-between;

  .desc {
    font-weight: bolder;
  }
}

.table {
  margin: 15px 0;
}
</style>
